package com.lkq.mongodb_comment.dao.impl;

import com.lkq.mongodb_comment.dao.CommentDao;
import com.lkq.mongodb_comment.entity.Comment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository("commentDao")
public class CommentDaoImpl implements CommentDao {
    @Autowired
    private MongoTemplate mongoTemplate;
    @Override
    public List<Comment> findAll() {
        return mongoTemplate.findAll(Comment.class);
    }

    @Override
    public Comment getComment(String id) {
        return mongoTemplate.findOne(new Query(Criteria.where("_id").is(id)),Comment.class);
    }

    @Override
    public void update(Comment comment) {
       Criteria criteria = Criteria.where("_id").is(comment.get_id());
       Query query = new Query(criteria);
        Update update = Update.update("content",comment.getContent());
        mongoTemplate.updateMulti(query,update,Comment.class);
    }

    @Override
    public void insert(Comment comment) {
        mongoTemplate.insert(comment);
    }

    @Override
    public void insertAll(List<Comment> comment) {
        mongoTemplate.insertAll(comment);
    }

    @Override
    public void remove(String id) {
        Criteria criteria = Criteria.where("_id").is(id);
        Query query = new Query(criteria);
        mongoTemplate.remove(query,Comment.class);
    }
    @Override
    public long count(String id) {
        long count = mongoTemplate.count(new Query(Criteria.where("parentid").is(id)), Comment.class);
        return count;
    }
}